import { createSlice } from '@reduxjs/toolkit'
import { setToken as _setToken, getToken, removeToken } from '@/utils'
import { loginAPI, getProfileAPI } from '@/apis/user'

const userStore = createSlice({
	name: 'user',
	initialState: {
		token: getToken() || '',
		userInfo: {},
		status: 'idle',
		error: null
	},
	reducers: {
		setToken(state, action) {
			state.token = action.payload
			// localStorage 保存token
			_setToken(action.payload)
		},
		setUserInfo(state, action) {
			state.userInfo = action.payload
		},
		clearUser(state) {
			state.token = ''
			state.userInfo = {}
			removeToken()
		}
	}
})

const fetchLogin = (loginForm) => {
	return async (dispatch) => {
		// 调用登录接口，获取token
		const res = await loginAPI(loginForm)
		// 调用setToken action，设置token
		dispatch(setToken(res.data.token))
	}
}

const fetchUserInfo = () => {
	return async (dispatch) => {
		// 调用获取用户信息接口，获取用户信息
		const res = await getProfileAPI()
		// 调用setUserInfo action，设置用户信息
		dispatch(setUserInfo(res.data))
	}
}
// 解构出actions
export const { setToken, setUserInfo, clearUser } = userStore.actions

//获取reduce函数
export default userStore.reducer

export { fetchLogin, fetchUserInfo }